package org.sfans.admin.controller;

import java.util.UUID;

import org.sfans.core.domain.User;
import org.sfans.core.domain.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("users")
@Profile("admin")
public class CreateUserController {

	@Autowired
	private UserRepository repository;

	@Autowired
	private PasswordEncoder encoder;

	@RequestMapping(value = "create", method = RequestMethod.GET, params = { "username",
			"password" })
	public User create(@RequestParam(value = "username", required = true) final String username,
			@RequestParam(value = "password", required = true) final String password) {
		final User user = new User();
		user.setEmail(String.format("%s@163.com", UUID.randomUUID()));

		user.getAccount().setUsername(username);
		user.getAccount().setPassword(encoder.encode(password));
		user.getAccount().addAuthorities("ROLE_ADMIN");

		return repository.save(user);
	}
}
